/**
 *  使用  npm run gen
 *  读取当前文件里的./table/col.txt
 *  生成成功，在./table创建col.json
 */

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { chalk } = require('@vue/cli-shared-utils');
const { execSync } = require('child_process');

const generateFile = path.resolve(__dirname, 'table/gen-col.json');

const log = {
  info(msg) {
    console.log(chalk.green(msg));
  },
  error(msg) {
    console.log(chalk.red(msg));
  },
  warnning(msg) {
    console.log(chalk.yellow(msg));
  }
};

async function writeArrayJson(json) {
  const text = JSON.stringify(json);
  await fs.writeFileSync(generateFile, text, {
    encoding: 'utf-8'
  });
}

async function readFileSyncText() {
  const fileName = path.resolve(__dirname, 'table/col.txt');
  const file = fs.readFileSync(fileName, {
    encoding: 'utf-8'
  });
  return file;
}

async function generateTableJson() {
  const txt = await readFileSyncText();
  let arrTxt = txt.split('\n') || [];
  arrTxt = arrTxt.filter(item => item);
  const json = arrTxt.map((item = '') => {
    const tiems = item.split(' ');
    return {
      field: tiems[1] || tiems[0],
      headerName: tiems[0],
      editable: false
    };
  });
  // console.log(txt);
  await writeArrayJson(json);
}

async function generateSearchJson() {
  const txt = await readFileSyncText();
  let arrTxt = txt.split('\n') || [];
  arrTxt = arrTxt.filter(item => item);
  const json = arrTxt.map((item = '') => {
    const tiems = item.split(' ');
    return {
      label: tiems[0],
      prop: tiems[0],
      elementType: !tiems[1] ? 'input' : tiems[1] === 1 ? 'singleInput' : 'multiInput'
    };
  });
  // console.log(txt);
  await writeArrayJson(json);
}

async function start() {
  console.log(process.argv);
  const status = process.argv[2];
  log.info('读取文件...');
  if (status === 's') {
    await generateSearchJson();
  } else {
    await generateTableJson();
  }
  log.info('生成成功，正在格式化...');
  await execSync(`npx prettier --write ${generateFile}`);
  log.info('格式化成功');
}

start(process.argv);
